<template>
    <div class="data-table-container">
        <!-- 顶部操作栏 -->
        <div class="header-actions">
            <el-button :disabled="!hasCustomSort" icon="refresh" @click="resetSort">
                重置排序
            </el-button>
            <el-button type="primary" :loading="loading" :disabled="!allData.length" @click="handleExport">
                导出数据
                <template #icon>
                    <el-icon class="el-icon--right">
                        <SvgIcon icon="download" />
                    </el-icon>
                </template>
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table ref="table" v-loading="loading" :data="paginatedData" border style="width: 100%; flex: 1 1 auto;"
            @sort-change="handleSortChange" :max-height="tableMaxHeight">
            <el-table-column prop="time" label="时间" min-width="180" sortable="custom">
                <template #default="scope">
                    {{ formatTime(scope.row.time) }}
                </template>
            </el-table-column>

            <el-table-column prop="value" label="流量量" min-width="120" sortable="custom">
                <template #default="scope">
                    {{ formatValue(scope.row.value) }}
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="totalItems" layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>
<script setup>
import { ref, computed, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import * as XLSX from 'xlsx'
import { getMeterDetailApi } from '@/api/meter'
import SvgIcon from '@/components/icon/SvgIcon.vue'

// Props 定义
const props = defineProps({
    id: {
        type: [String, Number],
        default: null
    },
    dateRange: {
        type: Array,
        default: () => []
    }
})

// 状态定义
const loading = ref(false)
const allData = ref([])  // 存储所有数据
const currentPage = ref(1)
const pageSize = ref(20)
const sortConfig = ref({
    prop: '',
    order: ''
})
const hasCustomSort = computed(() => sortConfig.value.prop !== '')

// 计算总条目数
const totalItems = computed(() => allData.value.length)

// 排序后的数据
const sortedData = computed(() => {
    let data = [...allData.value]
    if (sortConfig.value.prop) {
        data.sort((a, b) => {
            let aVal = a[sortConfig.value.prop]
            let bVal = b[sortConfig.value.prop]

            if (sortConfig.value.prop === 'time') {
                aVal = new Date(aVal).getTime()
                bVal = new Date(bVal).getTime()
            }

            if (sortConfig.value.order === 'ascending') {
                return aVal > bVal ? 1 : -1
            } else {
                return aVal < bVal ? 1 : -1
            }
        })
    }
    return data
})

// 分页后的数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return sortedData.value.slice(start, end)
})

// 计算用量
const calculateUsage = (prevValue, currentValue) => {
    if (prevValue === undefined || prevValue === null) {
        return 0
    }
    return currentValue - prevValue
}

// 格式化时间
const formatTime = (time) => {
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化数值
const formatValue = (value) => {
    return parseFloat(value).toFixed(2) + 'm³'
}

// 获取数据
const fetchMeterData = async (id, startDate, endDate) => {
    loading.value = true
    try {
        const res = await getMeterDetailApi({
            id: id,
            start_time: startDate,
            end_time: endDate
        })

        if (res.code !== 200) {
            ElMessage.error(res.message || '获取数据失败')
            
            return
        }

        // 处理数据
        allData.value = res.meter_readings
            .map((item, index) => {
                const prevValue = index === 0 ? item.value : res.meter_readings[index - 1].value
                return {
                    value: calculateUsage(prevValue, item.value),
                    time: item.time
                }
            }).slice(1)
    } catch (error) {
        
        ElMessage.error('服务器异常，获取数据失败')
    } finally {
        loading.value = false
    }
}

// 导出数据为Excel
const handleExport = async () => {
    if (!allData.value.length) {
        ElMessage.warning('没有可导出的数据')
        return
    }

    try {
        loading.value = true

        // 处理导出数据
        const exportData = allData.value.map(item => ({
            '时间': formatTime(item.time),
            '用量': formatValue(item.value)
        }))

        // 创建工作簿和工作表
        const wb = XLSX.utils.book_new()
        const ws = XLSX.utils.json_to_sheet(exportData)

        // 设置列宽
        const colWidths = [
            { wch: 20 }, // 时间列宽
            { wch: 15 }  // 用量列宽
        ]
        ws['!cols'] = colWidths

        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '用量数据')

        // 导出Excel文件
        XLSX.writeFile(wb, `meter_readings_${dayjs().format('YYYYMMDD_HHmm')}.xlsx`)

        ElMessage.success('导出成功')
    } catch (error) {
        
        ElMessage.error('导出失败：' + (error.message || '未知错误'))
    } finally {
        loading.value = false
    }
}

// 处理排序
const handleSortChange = ({ prop, order }) => {
    sortConfig.value = { prop, order }
}
let table = ref(null)
// 重置排序
const resetSort = () => {
    sortConfig.value = { prop: '', order: '' }
    table.value.clearSort()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

// 计算表格的最大高度（可选，根据需求调整）
const tableMaxHeight = computed(() => {
    // 假设容器高度为 100vh，可以根据实际情况调整
    return 'calc(100vh - 200px)' // 示例：减去顶部和底部的固定高度
})

// 监听属性变化
watchEffect(() => {
    if (props.dateRange.length === 2 && props.id) {
        currentPage.value = 1 // 重置页码
        sortConfig.value = { prop: '', order: '' } // 重置排序
        fetchMeterData(props.id, props.dateRange[0], props.dateRange[1])
    }
})
</script>
<style scoped>
.data-table-container {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    border-radius: 4px;
}

.header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.el-table {
    flex: 1 1 auto;
    overflow: auto;
}
</style>
